package com.ruoyi.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {

    private static final String randChars = "0123456789abcdefghigklmnopqrstuvtxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
    private static Random random = new Random();
    // 邮箱正则表达式
    private static String emailRegex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{ueditor,}$";
    // 手机号码表达式
    private static String mobileRegex = "^((1[3-9][0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

    private static AtomicInteger orderIdCount = new AtomicInteger();

    private static final String sftpImgUrl = "/home/images";
    /**
     * 上传文件路径
     */
    private static final String uploadFileUrl = "E:/file";
    /**
     * 判断是否为空
     * @param obj Object
     * @return 空 = true，不为空 = false
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String && (obj.equals("") )) {
            return true;
        } else if (obj instanceof Boolean && !((Boolean) obj)) {
            return true;
        } else if (obj instanceof Collection && ((Collection<?>) obj).isEmpty()) {
            return true;
        } else if (obj instanceof Map && ((Map<?,?>) obj).isEmpty()) {
            return true;
        } else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
            return true;
        }
        if("null".equals(obj)){
            return true;
        }
        return false;
    }

    /**
     * 获取随机字符
     * @param length 随机字符长度
     * @param isOnlyNum 是否只是数字
     * @return 随机字符串
     */
    public static String getRandStr(int length, boolean isOnlyNum) {
        int size = isOnlyNum ? 10 : 62;
        StringBuffer hash = new StringBuffer(length);
        for (int i = 0; i < length; i++) {
            hash.append(randChars.charAt(random.nextInt(size)));
        }
        return hash.toString();
    }

	public static   String getFeeNoByUUId() {
		int machineId = 1;//最大支持1-9个集群机器部署
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if(hashCodeV < 0) {//有可能是负数
			hashCodeV = - hashCodeV;
		}
		// 0 代表前面补充0
		// 4 代表长度为4
		// d 代表参数为正数型
		return machineId + String.format("%015d", hashCodeV);
	}

	/**
	 * 获取时间差(小时)
	 * @param time 需要比较的时间
	 * @return 随机字符串
	 */
	public static Long getHourByTimeAndNow(Date time) {
		Long now = (new Date().getTime()-time.getTime())/(1000*60*60); //小时
		return now;
	}
	public static Long getHourByTime(Date startTime,Date endTime) {
		Long now = (endTime.getTime()-startTime.getTime())/(1000*60*60); //小时
		return now;
	}
	/**
	 * 14:33:00 是否在 09:30:00 - 12:00:00 内
	 *
	 * @param str1  14:33:00
	 * @param round 09:30:00 - 12:00:00
	 */
	public static boolean timeIsInRound(String str1, String round) {
		String[] roundTime = round.split(" - ");
		return timeIsInRound(str1, roundTime[0], roundTime[1]);
	}
	/**
	 * 比较一个 HH:mm:ss 是否在一个时间段内
	 * 如：14:33:00 是否在 09:30:00 和 12:00:00 内
	 */
	public static boolean timeIsInRound(String str1, String start, String end) {
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		Date now = null;
		Date beginTime = null;
		Date endTime = null;

		try {
			now = df.parse(str1);
			beginTime = df.parse(start);
			endTime = df.parse(end);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return belongCalendar(now, beginTime, endTime);
	}

	/**
	 * 判断时间是否在时间段内
	 */
	public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);

		Calendar begin = Calendar.getInstance();
		begin.setTime(beginTime);

		Calendar end = Calendar.getInstance();
		end.setTime(endTime);

		return date.after(begin) && date.before(end);
	}
	/**
	 * 获取随机字符
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @return 随机字符串
	 */
	public static String getDayHourMin(Date startTime,Date endTime) {
		Long totalTime = endTime.getTime()-startTime.getTime();
		long day = totalTime / (24 * 60 * 60 * 1000);
		long hour = (totalTime / (60 * 60 * 1000) - day * 24);
		long min = ((totalTime / (60 * 1000)) - day * 24 * 60 - hour * 60);
		String str = day + "天" + hour + "小时" + min + "分";
		return str;
	}


	/**
     * 获取时间差(分钟)
     * @param time 需要比较的时间
     * @return 随机字符串
     */
    public static Long getMinByTimeAndNow(Date time) {
        Long now = (new Date().getTime()-time.getTime())/(1000*60); //分钟
        return now;
    }

    /**
     * 验证邮箱格式
     * @param email 待验证的字符串
     * @return 如果是符合邮箱格式的字符串,返回<b>true</b>,否则为<b>false</b>
     */
    public static boolean isEmail(String email) {
        return match(emailRegex, email);
    }

    /**
     * 验证手机号码
     * @param mobiles 待验证的字符串
     * @return 如果是符合手机号码格式的字符串,返回<b>true</b>,否则为<b>false</b>
     */
    public static boolean isMobile(String mobiles) {
        return match(mobileRegex, mobiles);
    }

    /**
     * @param regex 正则表达式字符串
     * @param str 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    private static boolean match(String regex, String str) {
        if(isEmpty(str)){
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 获取IP4
     * @param request
     * @return IP地址
     */
    public static String getIP4(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "本地";
        }else
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 数组根据表达式转换为String
     * @param list
     * @param exp
     * @return
     */
    public static String listToString(List<?> list , String exp) {
        StringBuffer resourceIdsSB = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            resourceIdsSB.append(list.get(i));
            if(i < list.size() -1){
                resourceIdsSB.append(exp);
            }
        }
        return resourceIdsSB.toString();
    }

    public static synchronized String createOrderID(){
        Random random = new Random();
        Integer number = random.nextInt(900000) + 100000;
        return System.currentTimeMillis() + String.valueOf(number);
    }
    public static synchronized String createCode(String code){
        Random random = new Random();
        Integer number = random.nextInt(9000) + 1000;
        return code+ String.valueOf(number);
    }


    /**
     * 生成密码
     */
    public static String createPassword(String username,String password){
        return   Md5Util.encode(username+password);
    }

    public final static Integer psInt(Object obj){
        if(obj==null||"".equals(obj.toString()))
            return null;
        return Integer.parseInt(obj.toString());
    }

    public final static String psString(Object obj){
        return obj==null ? null:obj.toString();
    }

    public final static Long psLong(Object obj){
        if(obj==null||"".equals(obj.toString()))
            return null;
        return Long.parseLong(obj.toString());
    }

    public final static Float psFloat(Object obj){
        if(obj==null||"".equals(obj.toString()))
            return null;
        return Float.parseFloat(obj.toString());
    }

    public final static Short psShort(Object obj){
        if(obj==null||"".equals(obj.toString()))
            return null;
        return Short.parseShort(obj.toString());
    }

    /**
     * 获取一定长度的随机字符串
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 根据单号生成下一个取单号
     * @param no
     * @return
     */
    public static String takeCode(String no){
        String zms[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        String tackCode="A01";
        if(CommonUtil.isEmpty(no)){
            return tackCode;
        }
        String zm=no.substring(0,1);
        Integer num=Integer.parseInt(no.substring(1,no.length()));
        if(num<99){
            num++;
            if(num<10){
                tackCode=zm+"0"+num;
            }else {
                tackCode=zm+num;
            }
        }else {
            for (int i=0;i<zms.length;i++){
                if(zm.equals(zms[i])){
                    zm=zms[i+1];
                    return zm+"01";
                }
            }
        }
        return tackCode;
    }
    public static String dateToStr(Date datetime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(datetime);
        return dateString;
    }

    public static Date strToDate(String strDate)throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.parse(strDate);
    }

    //生成16位随机数字码
    public static String getSixteenByUUId() {
        int random = (int) (Math.random()*9+1);
        String valueOf = String.valueOf(random);
        //生成uuid的hashCode值
        int hashCode = UUID.randomUUID().toString().hashCode();
        //可能为负数
        if(hashCode<0){
            hashCode = -hashCode;
        }
        String value = valueOf + String.format("%015d", hashCode);
        return value;
    }
    public static String genMerOrderId(String msgId) {
        String date = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
        int i = orderIdCount.incrementAndGet()%1000;
        if(i<1000)
            i+=1000;
        return msgId + date + i;
    }

    /**
     * @Author wangghua
     * @Description 比较时间大小
     * @Date 17:55 2021/7/30
     * @Param [startTime, endTime]
     * @return boolean
     **/
	public static boolean compareTime(Date startTime, Date endTime) {
    	if (isEmpty(startTime) || isEmpty(endTime)){
			return false;
		}
    	if (startTime.getTime()>endTime.getTime()){
    		return false;
		}
    	return true;
	}
}
